package com.xd.Util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component
public class JwtUtil {
    @Value("${app.jwt.secret}")
//    安全密钥
    private  String secret;
//   token过期时间是半个小时
    private final static Long TIME_OUT=60*30*100000000000L;
//    创建token令牌
    public String generateToken(String username){
        return JWT.create()
                .withSubject(username)
                .withExpiresAt(new Date(System.currentTimeMillis()+ TIME_OUT))
                .sign(Algorithm.HMAC512(secret.getBytes()));

    }
//    解析token方法
    public String getUsernameFromToken(String token){
        return JWT.require(Algorithm.HMAC512(secret.getBytes()))
                .build()
                .verify(token.replace("Bearer ",""))
                .getSubject();
    }


}
